package cn.fay.chapter18;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Random;
class Data implements Serializable{
	private int n;
	public Data(int n) {
		this.n = n;
	}
	public String toString() {
		return Integer.toString(n);
	}
}
public class Worm implements Serializable {
	private static Random r=new Random();
	private Data[] d={new Data(r.nextInt(10)),new Data(r.nextInt(10)),new Data(r.nextInt(10))};
	private Worm next;
	private char c;
	public Worm(int i, char c) {
		System.out.println("Worm constructor: "+i);
		this.c = c;
		if (--i>0) {
			next=new Worm(i, (char)(c+1));
		}
	}
	public Worm() {
		System.out.println("Default constructor");
	}
	public String toString() {
		StringBuilder sb=new StringBuilder(":");
		sb.append(c).append("(");
		for (Data dat : d) 
			sb.append(dat);
		sb.append(")");
		if (next!=null) 
			sb.append(next);
		return sb.toString();
	}
	
	public static void main(String[] args) throws Exception{
		Worm w=new Worm(6, 'a');
		System.out.println("w= "+w);
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("worm.out"));
		out.writeObject("Worm storage\n");
		out.writeObject(w);
		out.close();
		ObjectInputStream in=new ObjectInputStream(new FileInputStream("worm.out"));
		String s=(String) in.readObject();
		Worm w2=(Worm) in.readObject();
		System.out.println(s+"w2= "+w2);
		
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		ObjectOutputStream out2=new ObjectOutputStream(baos);
		out2.writeObject("Worm storage in cache\n");
		out2.writeObject(w);
		out2.flush();
		ObjectInputStream in2=new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
		s=(String) in2.readObject();
		Worm w3=(Worm) in2.readObject();
		System.out.println(s+"w3= "+w3);
	}
}
